package com.stock.api.shiro;


import com.stock.api.domain.sys.SysUserBean;
import com.stock.api.service.sys.SysRoleRelService;
import com.stock.api.service.sys.SysUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;

public class MyRealm extends AuthorizingRealm {

//    @Resource
    private SysRoleRelService sysRoleRelService;

    private SysUserService sysUserService;

//	@Resource
//	private SysMenuService sysMenuService;

    /**
     * 用户权限、角色验证
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String userName = (String) principals.getPrimaryPrincipal();
        SysUserBean sysUserBean = sysUserService.selectByEmailOrPhone(userName, null);
        if (sysUserBean != null) {
            SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
            //获取用户角色列表
            authorizationInfo.setRoles(sysRoleRelService.selectRoleByUserId(sysUserBean.getId()));
            //获取用户权限
//			List<SysMenuDto> menuDtoList = sysMenuService.selectMenusByUserId(sysUserBean.getId());
//			authorizationInfo.setStringPermissions(new HashSet(menuDtoList));
            return authorizationInfo;
        }
        return null;
    }

    /**
     * 用户验证登录
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String userName = (String) token.getPrincipal();
        SysUserBean sysUserBean = sysUserService.selectByEmailOrPhone(userName, null);
        if (sysUserBean != null) {
            AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(sysUserBean.getUserName(), sysUserBean.getPwd(), "xx");
            return authcInfo;
        } else {
            return null;
        }
    }

    public void setSysRoleRelService(SysRoleRelService sysRoleRelService) {
        this.sysRoleRelService = sysRoleRelService;
    }

    public void setSysUserService(SysUserService sysUserService) {
        this.sysUserService = sysUserService;
    }
}
